package com.travel.utils;

import com.alibaba.fastjson2.JSONObject;
import com.travel.entity.po.User;
import com.travel.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @Author:Jasenon_ce
 * @Date: 2025/03/13/下午4:38
 */
public class JWTUtil {
    private static final String SECRET_KEY = "Travel_System_Extended_Secret_Key_For_JWT_Signing_12345";

    public static String generateToken(String subject) {
        return Jwts.builder()
                .subject(subject)
                .issuedAt(new Date(System.currentTimeMillis()))
                .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 ))// 设置过期时间,30天
                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8)))
                .build()
                .parseSignedClaims(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static User getUser(String token) {
        try {
            Claims claims = Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8)))
                .build()
                .parseSignedClaims(token)
                .getPayload();

            String json = claims.getSubject();
            return JSONObject.parseObject(json, User.class);
        } catch (Exception e) {
            throw new BusinessException("参数错误！");
        }
    }
}
